package com.example.p2p.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.os.SystemClock;
import android.provider.Settings;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.p2p.R;
import com.example.p2p.bean.UpdateInfo;
import com.example.p2p.view.CustomHorizontalProgresWithNum;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;

import butterknife.Bind;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;

public class WelcomeActivity extends Activity {

    private static final int TO_MAIN = 1;
    private static final int DOWNLOAD_VERSION_SUCCESS = 2;
    private static final int DOWNLOAD_APK_FAIL = 3;
    private static final int DOWNLOAD_APK_SUCCESS = 4;
    private static final int INSTALL_PACKAGES_REQUESTCODE = 5;
    private static final int GET_UNKNOWN_APP_SOURCES = 6;
    @Bind(R.id.iv_welcome_icon)
    ImageView ivWelcomeIcon;
    @Bind(R.id.tv_welcome_version)
    TextView tvWelcomeVersion;
    @Bind(R.id.rl_welcome)
    RelativeLayout rlWelcome;
    @Bind(R.id.horizontalProgress)
    CustomHorizontalProgresWithNum horizontalProgress;
    private long startTime;
    private UpdateInfo updateInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        ButterKnife.bind(this);
        //提供启动动画
        setAnimation();
        //取消严格模式  FileProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
        //联网更新应用
        updateApkFile();
    }

    private void setAnimation() {
        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);//0：完全透明 1:完全不透明
        alphaAnimation.setDuration(3000);//保持3秒
        alphaAnimation.setInterpolator(new AccelerateDecelerateInterpolator());//设置动画的变化率

        //方式一
        alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }
            //当动画结束时：调用如下方法
            @Override
            public void onAnimationEnd(Animation animation) {
                Intent intent = new Intent(WelcomeActivity.this,MainActivity.class);
                startActivity(intent);
                finish();//销毁当前页面
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        //方式二
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                Intent intent = new Intent(WelcomeActivity.this,MainActivity.class);
//                startActivity(intent);
//                finish();//销毁当前页面
//            }
//        },3000);

        //启动动画
        rlWelcome.startAnimation(alphaAnimation);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TO_MAIN:
                    finish();
                    startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
                    break;
                case DOWNLOAD_VERSION_SUCCESS:
                    //获取当前应用的版本信息
                    String version = getVersion();
                    //更新页面版本号
                    //。。。。。。
                    //比较服务器获取的最新版本跟本应用的版本是否一致
                    if (version.equals(updateInfo.version)) {
                        Toast.makeText(WelcomeActivity.this, "当前版本已是最新版本！", Toast.LENGTH_SHORT).show();
                        toMain();
                    } else {
                        new AlertDialog.Builder(WelcomeActivity.this)
                                .setTitle("下载最新版本")
                                .setMessage(updateInfo.desc_apk)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        //下载服务器保存的应用数据
                                        downloadAPK();
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        toMain();
                                    }
                                })
                                .show();
                    }
                    break;
                case DOWNLOAD_APK_FAIL:
                    Toast.makeText(WelcomeActivity.this, "联网下载数据失败", Toast.LENGTH_SHORT).show();
                    toMain();
                    break;
                case DOWNLOAD_APK_SUCCESS:
                    Toast.makeText(WelcomeActivity.this, "下载数据成功", Toast.LENGTH_SHORT).show();
                    //隐藏进度条
//                    dialog.dismiss();
                    //检测Android版本号
                    checkOreo();
                    break;
            }
        }
    };


    @SuppressLint("CheckResult")
    private void checkOreo(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0
            //判断是否可以直接安装
            boolean canInstall = getPackageManager().canRequestPackageInstalls();
            if (canInstall) {
                //安装下载好的应用
                installAPK();
            } else {
                //请求安装未知应用来源的权限
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);
            }
        } else {
            //安装apk
            installAPK();
        }
    }

    private void installAPK() {
        if (!apkFile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
//      安装完成后，启动app（源码中少了这句话）
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.parse("file://" + apkFile.toString());
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(intent);
        finish();
    }

    private ProgressDialog dialog;
    private File apkFile;


    private void downloadAPK() {
        //初始化水平进度条
//        dialog = new ProgressDialog(this);
//        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//        dialog.show();
        horizontalProgress.setVisibility(View.VISIBLE);
        horizontalProgress.setProgress(0);
        File filesDir;
        //初始化数据要保存的位置
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            filesDir = this.getExternalFilesDir("");
        } else {
            filesDir = this.getFilesDir();
        }
        apkFile = new File(filesDir, "app-debug.apk");

        //启动一个分线程联网下载数据
        new Thread() {
            @Override
            public void run() {
                String path = updateInfo.apk_url;
                InputStream is = null;
                FileOutputStream fos = null;
                HttpURLConnection conn = null;
                try {
                    URL url = new URL(path);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    conn.connect();
                    if (conn.getResponseCode() == 200) {
//                        dialog.setMax(conn.getContentLength());//设置dialog的最大值
                        float max = conn.getContentLength();
                        horizontalProgress.setMax(100);
                        is = conn.getInputStream();
                        fos = new FileOutputStream(apkFile);
                        byte[] buffer = new byte[1024];
                        float len;
                        float a = 0.00f;
                        while ((len = is.read(buffer)) != -1) {
                            //更新dialog的进度
//                            dialog.incrementProgressBy(len);
                            a = a+len*100/max;
                            int b = 0;
                            if ((int)a>b){
                                b = (int) a;
                            }

                            horizontalProgress.setProgress(b);
                            fos.write(buffer, 0, (int) len);
                            SystemClock.sleep(1);
                        }
                        handler.sendEmptyMessageDelayed(DOWNLOAD_APK_SUCCESS, 0);

                    } else {
                        handler.sendEmptyMessageDelayed(DOWNLOAD_APK_FAIL, 0);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }.start();
    }

    /**
     * 获取当前版本号
     *
     * @return版本号
     */
    private String getVersion() {
        String version = "未知版本";
        PackageManager manager = getPackageManager();
        try {
            PackageInfo packageInfo = manager.getPackageInfo(getPackageName(), 0);
            version = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            //如果找不到对应的应用包信息，就返回“未知版本”
            e.printStackTrace();
        }
        return version;
    }



    private void updateApkFile() {
        //1.判断手机是否可以联网
        final Boolean connect = isConnect();
        if (!connect) {//没有网络
            //获取当前系统时间
            startTime = System.currentTimeMillis();
            Toast.makeText(this, "当前没有网络", Toast.LENGTH_SHORT).show();
            toMain();

        } else {//有移动网络
            //联网获取服务器的最新版本数据

                    AsyncHttpClient client = new AsyncHttpClient();
                    client.get("http://114.55.249.135:8888/apk_newest", new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                            //解析json数据
                            String jsonData = new String(responseBody);
                            try {
                                JSONObject jsonObject = new JSONObject(jsonData);
                                String resultCode = jsonObject.getString("status");
                                if (resultCode.equals("204")) {
                                    String data = jsonObject.getString("data");
                                    updateInfo = JSON.parseObject(data, UpdateInfo.class);
                                    handler.sendEmptyMessageDelayed(DOWNLOAD_VERSION_SUCCESS, 0);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                            Toast.makeText(WelcomeActivity.this, "联网请求数据失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }


    }

    private void toMain() {
        long currentTime = System.currentTimeMillis();
        long delayTime = 3000 - (currentTime - startTime);
        if (delayTime < 0) {
            delayTime = 0;
        }
        handler.sendEmptyMessageDelayed(TO_MAIN, delayTime);
    }

    //判断是否联网
    private Boolean isConnect() {
        Boolean connect = false;
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null) {
            connect = networkInfo.isConnected();
        }
        return connect;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case GET_UNKNOWN_APP_SOURCES:
                    checkOreo();
                    break;
            }
        }
    }
    //为了避免出现内存的泄漏，需要在onDestroy()中，移除所有未被执行的消息
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //方式一：
//        handler.removeMessages(WHAT_RESET_BACK);//移除指定id的所有的消息
        //方式二：移除所有的未被执行的消息
        handler.removeCallbacksAndMessages(null);
    }
}
